#include <opencv2/opencv.hpp>
#include <iostream>

int main() {
    // 打开视频文件
    cv::VideoCapture cap = cv::VideoCapture("../big_buck_bunny_720p_1mb.mp4");

    // 如果打开失败则退出
    if (!cap.isOpened()) {
        std::cerr << "Error: Could not open video file." << std::endl;
        return -1;
    }

    // 获取视频参数
    double width = cap.get(cv::CAP_PROP_FRAME_WIDTH);
    double height = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
    double fps = cap.get(cv::CAP_PROP_FPS);
    int fourcc = static_cast<int>(cap.get(cv::CAP_PROP_FOURCC)); // 获取原始视频的编码格式

    std::cout << "Video Parameters:" << std::endl;
    std::cout << "Resolution: " << width << "x" << height << std::endl;
    std::cout << "FPS: " << fps << std::endl;

    // 创建 VideoWriter 对象，指定输出文件名、编码格式、帧率和分辨率
    cv::VideoWriter writer;
    std::string outputFile = "output.avi";
    writer.open(outputFile, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), fps, cv::Size(static_cast<int>(width), static_cast<int>(height)));

    // 检查 VideoWriter 是否打开成功
    if (!writer.isOpened()) {
        std::cerr << "Error: Could not open the video writer." << std::endl;
        return -1;
    }

    // 根据视频帧率计算默认延迟时间
    int delay = (fps > 0) ? static_cast<int>(1000 / fps) : 30;
    std::cout << "Video FPS: " << fps << ", Default delay: " << delay << "ms" << std::endl;

    while (true) {
        cv::Mat frame;
        bool ret = cap.read(frame); // 读取视频帧
        if (!ret) {
            std::cout << "End of video or cannot read the frame." << std::endl;
            break;
        }

        // 将当前帧写入到输出视频文件
        writer.write(frame);

        // 显示帧
        cv::imshow("Video", frame);

        // 按键控制播放速度
        char key = static_cast<char>(cv::waitKey(delay));
        if (key == 'q') { // 按 'q' 键退出
            break;
        } else if (key == '+') { // 按 '+' 键加速
            delay = std::max(1, delay - 10); // 最小延迟为 1ms
            std::cout << "Speed up: delay = " << delay << "ms" << std::endl;
        } else if (key == '-') { // 按 '-' 键减速
            delay += 10;
            std::cout << "Slow down: delay = " << delay << "ms" << std::endl;
        }
    }

    // 释放资源
    cap.release();
    writer.release(); // 关闭视频写入器
    cv::destroyAllWindows();

    std::cout << "Video saved to " << outputFile << std::endl;
    return 0;
}
